import { ref, watch } from 'vue'
import { usePreferredDark } from '@vueuse/core'
import { defaultTheme, darkTheme } from '@/styles/theme'

export function useTheme() {
  const isDark = ref(usePreferredDark().value)
  const currentTheme = ref(isDark.value ? darkTheme : defaultTheme)
  
  // 应用主题到CSS变量
  const applyTheme = (theme) => {
    const root = document.documentElement
    
    // 应用颜色
    Object.entries(theme.colors).forEach(([key, value]) => {
      if (typeof value === 'object') {
        Object.entries(value).forEach(([subKey, subValue]) => {
          root.style.setProperty(`--color-${key}-${subKey}`, subValue)
        })
      } else {
        root.style.setProperty(`--color-${key}`, value)
      }
    })

    // 应用字体
    Object.entries(theme.typography.fontSize).forEach(([key, value]) => {
      root.style.setProperty(`--font-size-${key}`, value)
    })

    // 应用间距
    Object.entries(theme.spacing).forEach(([key, value]) => {
      root.style.setProperty(`--spacing-${key}`, value)
    })

    // 应用圆角
    Object.entries(theme.borderRadius).forEach(([key, value]) => {
      root.style.setProperty(`--radius-${key}`, value)
    })

    // 应用阴影
    Object.entries(theme.shadows).forEach(([key, value]) => {
      root.style.setProperty(`--shadow-${key}`, value)
    })

    // 应用z-index
    Object.entries(theme.zIndex).forEach(([key, value]) => {
      root.style.setProperty(`--z-${key}`, value)
    })
  }
  
  // 监听主题变化
  watch(isDark, (newValue) => {
    if (newValue) {
      document.documentElement.classList.add('dark')
      currentTheme.value = darkTheme
    } else {
      document.documentElement.classList.remove('dark')
      currentTheme.value = defaultTheme
    }
    applyTheme(currentTheme.value)
  }, { immediate: true })

  // 切换主题
  const toggleTheme = () => {
    isDark.value = !isDark.value
  }

  // 获取主题变量
  const getThemeValue = (category, key, subKey = null) => {
    if (subKey !== null) {
      return currentTheme.value[category]?.[key]?.[subKey]
    }
    return currentTheme.value[category]?.[key]
  }

  return {
    isDark,
    currentTheme,
    toggleTheme,
    getThemeValue,
    // 便捷的获取方法
    getColor: (key, subKey = null) => getThemeValue('colors', key, subKey),
    getFontSize: (key) => getThemeValue('typography', 'fontSize', key),
    getSpacing: (key) => getThemeValue('spacing', key),
    getBorderRadius: (key) => getThemeValue('borderRadius', key),
    getShadow: (key) => getThemeValue('shadows', key),
    getZIndex: (key) => getThemeValue('zIndex', key),
  }
}
